package javase.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.attribute.UserDefinedFileAttributeView;

/**
 * 测试一下反射的性能
 * @author LiShaowen
 * @date 2020/9/7 16:58
 */
public class TestPerformance {
    // 正常方式
    private static void test01(){
        Person person  = new Person();
        long startTime = System.currentTimeMillis();
        // 循环十亿次
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            person.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("正常方式消耗时间"+(endTime-startTime)+"ms");
    }
    // 反射
    private static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Person person  = new Person();
        Class c = person.getClass();
        Method getName = c.getDeclaredMethod("getName");
        long startTime = System.currentTimeMillis();
        // 循环十亿次
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            getName.invoke(person,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式消耗时间"+(endTime-startTime)+"ms");
    }
    // 反射关闭权限检测
    private static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Person person  = new Person();
        Class c = person.getClass();
        Method getName = c.getDeclaredMethod("getName");
        getName.setAccessible(true);
        long startTime = System.currentTimeMillis();
        // 循环十亿次
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            getName.invoke(person,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式消耗时间"+(endTime-startTime)+"ms");
    }

    //反射
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {


        test01();
        test02();
        test03();
    }
}
